import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'
export default {
  namespaced: true,
  state: {
    // vuex持久化 与缓存结合
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    sendUserInfo(state, payload) {
      // 用 浅拷贝的方式去赋值对象 因为这样数据更新之后，才会触发组件的更新
      state.userInfo = { ...payload }
      console.log(state.userInfo)
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    login(context, payload) {
      return login(payload).then(data => {
        Message.success('登录成功')
        context.commit('setToken', data)
        // 登录成功时把时间戳存进Cookies缓存
        setTimeStamp()
      })
    },
    async getUserInfo(context) {
      const result = await getUserInfo()
      const baseInfo = await getUserDetailById(result.userId)
      const baseResult = {
        ...result,
        ...baseInfo
      }
      console.log(baseResult)
      context.commit('sendUserInfo', baseResult)
      // 加一个点睛之笔  这里这一步，暂时用不到，但是请注意，这给我们后边会留下伏笔
      return baseResult
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
      resetRouter()
      commit('permission/setRoutes', [], { root: true })
    }
  }
}
